import * as constants from './constants'
import Cookies from 'js-cookie'
import axios from 'axios'

const errorMsg = (msg) => ({
  type: constants.ERROR_MSG,
  msg
})

const success = (data) => ({
  type: constants.SUCCESS_AUTH,
  payload: data
})

const clear = () => ({
  type: constants.CLEAR_REDUX
})

export const register = ({ user, pwd, repeatPwd, type }) => {
  return (dispatch) => {
    if (!user || !pwd || !repeatPwd) {
      return dispatch(errorMsg('用户名和密码不能为空'))
    }
    if (pwd !== repeatPwd) {
      return dispatch(errorMsg('两次输入密码不一致'))
    }
    /*     dispatch(successReg({ user, pwd, type })) */
    axios.post('/user/register', { user, pwd, type })
      .then(res => {
        if (res.status === 200 && res.data.code === 0) {
          dispatch(success({ user, pwd, type }))
        } else {
          dispatch(errorMsg(res.data.msg))
        }
      })
  }
}

export const login = ({user, pwd}) => {
  return (dispatch) => {
    if ( !user || !pwd ) {
      return dispatch(errorMsg('账户密码不能为空'))
    }
    axios.post('/user/login',{user, pwd})
      .then(res => {
        if (res.status === 200 && res.data.code === 0 ){
          dispatch(success(res.data.data))
        }else{
          dispatch(errorMsg(res.data.msg)) 
        }
      })
  }
}

export const logout = () => {
  return (dispatch) => {
    Cookies.remove('userid',{path:''})
    dispatch(clear())
  }
}

export const loadinfo = (data) => ({
  type: constants.LOAD_INFO,
  payload: data
})

export const update = ({ title, company, avatar, desc, money }) => {
  return (dispatch) => {
    axios.post('/user/update', { title, company, avatar, desc, money }).then(res=>{
      if ( res.status === 200 && res.data.code === 0 ) {
        dispatch(success(res.data.data))
      }
    })
  }
}
export const list = (type) => {
  return (dispatch) => {
    debugger;
    axios.get(`/user/list?type=${type}`).then(res => {
      if(res.status === 200 && res.data.code === 0){
        dispatch(success({list:res.data.data}))
      }
    })
  }
}